package org.example.gen;

import org.example.LandEntity;
import org.example.LogInterface;
import org.example.ShapeEntity;
import org.example.area.AreaDto;
import org.example.area.AreaList;
import org.example.http.HttpUtil;
import org.example.http.ParamEntity;

import java.io.File;
import java.util.List;
import java.util.stream.Collectors;

import static org.example.tool.Base64ImageToPdf.TransformBase64ToPdf;

public class MapGen implements CallBack{

    private LogInterface log;
    private ShapeEntity shapeEntity;
    public MapGen(LogInterface log, ShapeEntity shapeEntity) {
        this.log = log;
        this.shapeEntity = shapeEntity;

    }

    @Override
    public boolean doWork(String nf, String bxgsmc, String qhdm, String zwmc, String dirPath) {
        List<LandEntity> lands = shapeEntity.getLands().stream().filter(
                landEntity -> landEntity.getNf().equals(nf) &&
                        landEntity.getBxgsmc().equals(bxgsmc) &&
                        landEntity.getQhdm().equals(qhdm) &&
                        landEntity.getZwmc().equals(zwmc)
        ).collect(Collectors.toList());
        if(lands.isEmpty()){
            log.logError(String.format("没有找到%s-%s的记录，无法生成专题图", qhdm, zwmc));
        }
        log.logInfo(String.format("正在生成专题图：%s-%s-%s-%s", nf,bxgsmc,qhdm,zwmc));
        File file = new File(dirPath);
        if (!file.exists()) {
            file.mkdirs();
        }

        try {
            AreaDto area = AreaList.getFullNameEntity(qhdm);
            ParamEntity paramEntity = ParamEntity.fromLandEntity(lands, area.getVillageName(), zwmc, nf);
            String base64=HttpUtil.httpPostQueryMap(paramEntity);
            //带有 data:image/png;base64,的base64转pdf
            String pdfName=dirPath+ File.separator+area.getCountyName() + area.getTownName()+area.getVillageName()+nf+zwmc+".pdf";
            System.out.println(getClass().getResource("/fonts/simsun.ttf").getFile());
            TransformBase64ToPdf(base64, pdfName,lands,getClass().getResource("/fonts/simsun.ttf").getFile());
            log.logSuccess(String.format("生成专题图成功：%s-%s-%s-%s", nf,bxgsmc,qhdm,zwmc));
        } catch (Exception e) {
            e.printStackTrace();
            log.logError(e.getMessage());
            log.logError(String.format("生成专题图失败：%s-%s-%s", nf, qhdm, zwmc));
            return false;
        }
        return true;
    }
}
